<?php

/**
 * Wraps an array of decorators with specified tag.
 *
 * Other options aside from 'children' will be passed to the HtmlTag decorator.
 * 
 * sample options:
 * array(
 *     'children' => array('Label', 'Errors', array('Description', array('tag' => 'span'))),
 *     'tag' => 'div',
 *     'class' => 'wrapper'
 * )
 *
 * @author    Mon Zafra <monzee at gmail>
 * @copyright (c)2009 Mon Zafra
 * @category  Mz
 * @package   Mz_Decorator
 * @license   http://mz-project.googlecode.com/svn/trunk/LICENSE     MIT License
 * @version   SVN: $Id: Wrap.php 3 2009-02-18 18:55:27Z monzee $
 */
class Mz_Decorator_Wrap extends Zend_Form_Decorator_Abstract
{
    public function render($content)
    {
        $element = $this->getElement();
        $placement = $this->getPlacement();
        $sep = $this->getSeparator();

        $toWrap = $this->getOption('children');

        $inside = '';
        $loader = $element->getPluginLoader(Zend_Form_Element::DECORATOR);
        foreach ($toWrap as $wrap) {
            if (is_array($wrap)) {
                $class = $loader->load($wrap[0]);
                $decorOpts = $wrap[1];
                $decorator = new $class($decorOpts);
            } else {
                $class = $loader->load($wrap);
                $decorator = new $class;
            }
            $decorator->setElement($element);
            $inside = $decorator->render($inside);
        }

        $tagOpts = $this->getOptions();
        $tagOpts['placement'] = 'wrap';
        unset($tagOpts['children']);
        if (empty($tagOpts['tag'])) {
            $tagOpts['tag'] = 'div';
        }
        
        $tagDecor = new Zend_Form_Decorator_HtmlTag($tagOpts);
        $wrapped = $tagDecor->render($inside);

        switch ($placement) {
            case self::APPEND:
                return $content . $sep . $wrapped;
                break;
            case self::PREPEND:
                return $wrapped . $sep . $content;
                break;
            default:
                return $wrapped . $sep;
                break;
        }
    }

}
